package com.ykdl.member.kid.person;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.ykdl.member.kid.R;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.adapters.DiaryAdapter;
import com.ykdl.member.kid.beans.DiaryBean;
import com.ykdl.member.kid.beans.DiaryListBean;
import com.ykdl.member.kid.beans.DiaryListBeanDay;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.circle.LookImageActivity;
import com.ykdl.member.kid.fittool.BaseActivity;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class AngleDiaryActivity extends BaseActivity implements OnClickListener, OnRefreshListener, OnItemClickListener{

	public static final String TAG = AngleDiaryActivity.class.getSimpleName();
	
	private RefreshListView mListView;
	private CameraHelp mCameraHelp = new CameraHelp(this);
	private ProgressDialog mProgressDialog;
	
	private int cursor = 0;
	private int total_number = 0;
	private DiaryAdapter mAdapter;
	private DiaryListTag mTag;
	
	private String mImagePath;
	private Button mBtnUpload;
	private boolean self;
	
	private int actor_id = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_angle_diary);
		actor_id = getIntent().getIntExtra("actor_id", 0);
		if (actor_id == 0) {
			self = true;
		} else {
			self = false;
		}
		initView();
		mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading_data));
		mTag = new DiaryListTag();
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (actor_id == 0) {
			Network.getInstance().requestSelfDiary(mTag);
		} else {
			Network.getInstance().requestUserDiary(mTag, actor_id);
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	private void initView(){
		findViewById(R.id.btnBack).setOnClickListener(this);
		mBtnUpload = (Button) findViewById(R.id.btnUpLoad);
		mBtnUpload.setOnClickListener(this);
		if (!self) {
			mBtnUpload.setVisibility(View.GONE);
		}
		mListView = (RefreshListView) findViewById(R.id.listView); 
		mAdapter = new DiaryAdapter(this);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		mListView.setonRefreshListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBack:
			finish();
			break;
		case R.id.btnUpLoad:
			showDialog(DIALOG_IMAGE_SELECT);
			break;
		default:
			break;
		}
	}
	
	public static int DIALOG_IMAGE_SELECT = 1;
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			String[] items = {"拍照", "从相册中取"};
			Dialog dialog = new AlertDialog.Builder(this).setTitle("请选择获取图片的方式")
				.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							mCameraHelp.startCamera(KidConfig.TPOIC_PATH, false);
						} else {
							mCameraHelp.startPhoto(KidConfig.TPOIC_PATH);
						}
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).create();
			return dialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == -1) {
			try {
				mImagePath = mCameraHelp.setPicture(requestCode, resultCode, data);
				// 第一次是拍照或者选择照片 回来，第二次才是 裁剪完成
				Log.e("alan", "------------------path:"+mImagePath);
				if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
				//裁剪完成的.
				}
				File file = new File(mImagePath);
				putphoto(file);
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				// System.gc();
				mImagePath = null;
			}
			if (mImagePath != null) {
			}
		}
	}
	
	public void putphoto(File file) {
		mProgressDialog = ProgressDialog.show(this, null, "正在上传...");
		String  pageurl = KidConfig.UPLOAD_PHOTO;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadFile(pageurl,file);
		TaskManager.startHttpRequest(request, new PutphotoTag(),  FileMetas.class);
	}
	
	class PutphotoTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			mProgressDialog.dismiss();
			if (t instanceof FileMetas && ((FileMetas) t).getDownload_urls() != null) {
				FileMetas bean = (FileMetas)t;
				Network.getInstance().newDiary(1, 0, ((FileMetas) t).getFile_id(), new NewDiaryTag());
			} else {
				Toast.makeText(AngleDiaryActivity.this, "头像上传失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			Toast.makeText(AngleDiaryActivity.this, "头像上传失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class NewDiaryTag implements ITag<StatuResult>{

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null && t.getResult() == 0 && TextUtils.isEmpty(t.getDesc())) {
				Toast.makeText(AngleDiaryActivity.this, "新建日记成功", 1).show();
			} else {
				Toast.makeText(AngleDiaryActivity.this, "添加数据失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			mProgressDialog.dismiss();
			Toast.makeText(AngleDiaryActivity.this, "添加数据失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			
		}
		
	}
	
	private class DiaryListTag implements ITag<DiaryListBean> {

		@Override
		public void refreshUI(DiaryListBean t, DataState ds) {
			mProgressDialog.dismiss();
			if (t != null) {
				List<DiaryListBeanDay> itmes = t.getList();
				mAdapter.clean();
				mAdapter.addBeans(itmes);
				mAdapter.notifyDataSetChanged();
				if (t.getNext_cursor() == t.getTotal_number()) {
					mListView.setMoreButtoIsGon(true);
				} else {
					cursor = t.getNext_cursor();
				}
			} else {
				Toast.makeText(AngleDiaryActivity.this, "添加数据失败", 1).show();
			}
			onRefreshComplete();
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			mProgressDialog.dismiss();
			Toast.makeText(AngleDiaryActivity.this, "添加数据失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
		
	}

	public void onRefreshComplete(){
		mListView.onRefreshComplete();
	}
	
	@Override
	public void onRefresh() {
		Network.getInstance().requestSelfDiary(mTag);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		final DiaryListBeanDay bean = (DiaryListBeanDay) mAdapter.getItem(position - 1);
		List<DiaryBean> diarys = bean.getList();
		if (diarys.size() > 0) {
			Intent intent = new Intent(this, LookAngleImageActivity.class);
			intent.putExtra("list", (Serializable)diarys);
			intent.putExtra("self", self);
			startActivity(intent);
		}
	}
	
	
	
}
